#include "adc.h"
#include <stdio.h>

static int read_float(const char *path, float *out)
{
    FILE *f = fopen(path, "r");
    if (!f) return -1;
    if (fscanf(f, "%f", out) != 1) { fclose(f); return -1; }
    fclose(f);
    return 0;
}

static int read_first_float(const char *const *paths, int n, float *out)
{
    for (int i = 0; i < n; ++i) {
        if (paths[i] && read_float(paths[i], out) == 0) return 0;
    }
    return -1;
}

// iio:device3, channel 0 -> 电压
int read_voltage(float *volt)
{
    // Try input (already scaled)
    const char *in_paths[] = {
        "/sys/bus/iio/devices/iio:device3/in_voltage0_input",
    };
    float v = 0.0f;
    if (read_first_float(in_paths, (int)(sizeof(in_paths)/sizeof(in_paths[0])), &v) == 0) {
        *volt = v;
        return 0;
    }
    // Try raw + scale
    float raw = 0.0f, scale = 0.0f;
    if (read_float("/sys/bus/iio/devices/iio:device3/in_voltage0_raw", &raw) == 0 &&
        read_float("/sys/bus/iio/devices/iio:device3/in_voltage0_scale", &scale) == 0) {
        *volt = raw * scale; // 单位通常为 V
        return 0;
    }
    return -1;
}

// iio:device3, channel 1 -> 电流
int read_current(float *amp)
{
    // Try input
    const char *in_paths[] = {
        "/sys/bus/iio/devices/iio:device3/in_voltage1_input",
    };
    float v = 0.0f;
    if (read_first_float(in_paths, (int)(sizeof(in_paths)/sizeof(in_paths[0])), &v) == 0) {
        *amp = v; // 若该通道经标定为电流通道，则应为安培
        return 0;
    }
    // Try raw + scale (若为电流转换，scale 需按照驱动给出的单位换算)
    float raw = 0.0f, scale = 0.0f;
    if (read_float("/sys/bus/iio/devices/iio:device3/in_voltage1_raw", &raw) == 0 &&
        read_float("/sys/bus/iio/devices/iio:device3/in_voltage1_scale", &scale) == 0) {
        *amp = raw * scale; // 具体单位以驱动为准
        return 0;
    }
    return -1;
}

